﻿using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace FFmpegVideoClip.Lib.UtilityControlsTools
{
    public class TextBoxOnlyNumber
    {
        public static bool GetIsOnlyNumber(DependencyObject obj) => (bool)obj.GetValue(IsOnlyNumberProperty);
        public static void SetIsOnlyNumber(DependencyObject obj, bool value) => obj.SetValue(IsOnlyNumberProperty, value);
        
        public static readonly DependencyProperty IsOnlyNumberProperty = DependencyProperty.RegisterAttached("IsOnlyNumber", typeof(bool), typeof(TextBoxOnlyNumber), new PropertyMetadata(false, (sender, e) =>
        {
            if (sender is not TextBox textBox)
                return;
            bool NewValue = (bool)e.NewValue;
            textBox.SetValue(InputMethod.IsInputMethodEnabledProperty, !NewValue);
            textBox.PreviewTextInput -= TxtInput;
            if (NewValue)
            {
                textBox.PreviewTextInput += TxtInput;
            }
        }));
        private static void TxtInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
        }

    }
}
